package com.youwe.dao.common;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.youwe.model.common.PageModel;
import com.youwe.model.demo.User;

public class BaseDao {

	@Autowired
	private MongoOperations mongoTemplate;

	@SuppressWarnings("all")
	protected PageModel paginationQuery(Query query, Criteria criteria, List<Order> orders, PageModel pageMode,
			Class classa) {

		/**
		 * 生成Pageable插件对象
		 */
		Pageable pageable = null;
		if (orders != null) {
			Sort sort = new Sort(orders);
			query.with(sort);
			new PageRequest(pageMode.getCurrentPage(), pageMode.getPageSize(), sort);
		} else {
			pageable = new PageRequest(pageMode.getCurrentPage(), pageMode.getPageSize());
		}

		if (criteria != null) {
			query.addCriteria(criteria);
		}

		/**
		 * 查询总记录数
		 */
		int totalCount = (int) mongoTemplate.count(query, classa);

		/**
		 * 执行分页查询请求
		 */
		List<User> content = mongoTemplate.find(query.with(pageable), classa);

		pageMode.setTotalCount(totalCount);

		pageMode.setData(content);

		return pageMode;
	}

}
